package com.asseco.mio.core.webapp.controller;

import org.apache.commons.lang.StringUtils;
import org.appfuse.service.GenericManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
import org.appfuse.model.Role;

@Controller
@RequestMapping("/roleform*")
public class RoleFormController extends BaseFormController {
    private GenericManager<Role, Long> roleManager = null;

    @Autowired
    public void setRoleManager(@Qualifier("roleManager") GenericManager<Role, Long> roleManager) {
        this.roleManager = roleManager;
    }

    public RoleFormController() {
        setCancelView("redirect:roles");
        setSuccessView("redirect:roles");
    }

    @ModelAttribute
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    protected Role showForm(HttpServletRequest request)
    throws Exception {
        String id = request.getParameter("id");

        if (!StringUtils.isBlank(id)) {
            return roleManager.get(new Long(id));
        }

        return new Role();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(Role role, BindingResult errors, HttpServletRequest request,
                           HttpServletResponse response)
    throws Exception {
        if (request.getParameter("cancel") != null) {
            return getCancelView();
        }

        log.debug("entering 'onSubmit' method...");

        boolean isNew = (role.getId() == null);
        String success = getSuccessView();
        Locale locale = request.getLocale();

        if (request.getParameter("delete") != null) {
            roleManager.remove(role.getId());
            saveMessage(request, getText("role.deleted", locale));
        } else {
            roleManager.save(role);
            String key = (isNew) ? "role.added" : "role.updated";
            saveMessage(request, getText(key, locale));

            if (!isNew) {
                success = "redirect:roleform?id=" + role.getId();
            }
        }

        return success;
    }
}
